package com.aric.springbootmusic.filter;

import com.aric.springbootmusic.entity.pojo.User;
import com.aric.springbootmusic.jwt.JWTUtils;
import com.aric.springbootmusic.jwt.SecurityConstants;
import com.aric.springbootmusic.mapper.UserMapper;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

//@Order(value = Ordered.HIGHEST_PRECEDENCE)
@Order(0)
@Component
public class JwtFilter extends OncePerRequestFilter {
    @Autowired
    private UserMapper userMapper;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader(SecurityConstants.JWT_HEADER);
        //如果token不存在的话
        if(!StringUtils.hasText(token)){
            filterChain.doFilter(request,response);
            return;
        }
        //如果token存在的话
        Claims claims = JWTUtils.getClaims(token);
        String id = claims.getSubject();

        User user = userMapper.selectById(id);
        if(user.getStatus().getStatusCode()==1){
            throw new RuntimeException("token不正确，请重新登录");
        }

        String authorities = (String)claims.get("authorities");
        Authentication auth = new UsernamePasswordAuthenticationToken(id,null, AuthorityUtils.commaSeparatedStringToAuthorityList(authorities));
        SecurityContextHolder.getContext().setAuthentication(auth);
        filterChain.doFilter(request,response);
    }
}
